/// 
/// Controllers
/// -------------------------------------------------------------------------------------------------------------------
/// <reference path="_references.ts" />

angular.module('app.controllers', []);

'use strict';


function homeCtrl($rootScope) {
}

//todo's
//refactor duplciate code
//move more code into service
//figure out double call.
//replace add hack -- consider model and TeamMember see if adds to scope.
//add image add/delete.
//move show/hide to switch
//crud buttons to diredtives
function teamDetailCtrl($rootScope, $scope, $routeParams, TeamServices, AdminServices, logger) {
    $scope.team = [];

    $scope.teamid = $routeParams.id;
    $scope.addMode = false;
    $scope.isVisible = true;

    $scope.toggleVisible = function () {
        $scope.IsVisible = !$scope.IsVisible;
    };
    $scope.toggleAddMode = function () {
        $scope.addMode = !$scope.addMode;
    };
    $scope.toggleEditMode = function (TeamMember) {
        TeamMember.editMode = !TeamMember.editMode;
    };


    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };

    function GetTeam() {
        TeamServices.GetTeam({
            id: $routeParams.id
        }, function (successResult) {

            $scope.team = successResult;
            AddTitles();
        }, function (err) {
            DisplayError(err);
        });
    }



    if ($scope.team == undefined || !($scope.team.length > 0)) {
        GetTeam();
    };

    if ($scope.roles == undefined || !($scope.roles.length > 0)) {
        $scope.roles = AdminServices.GetByDesc({
            desc: 'team role'
        }, function (successResult) {
            for (var i = 0; i < $scope.team.people_TeamMember.length; i++) {

                if ($scope.team.people_TeamMember[i].defaultTeamRoleId != undefined) {
                    {
                        for (var m = 0; m < $scope.roles.length; m++) {
                            if ($scope.team.people_TeamMember[i].defaultTeamRoleId == $scope.roles[m].lookupID) {
                                $scope.team.people_TeamMember[i].lookup = $scope.roles[m].title;
                                break;
                            }
                        }
                    }
                    ///  $scope.engineer.currentActivity = $scope.activities[i];
                    ///  break;
                }
            }
        }, function (err) {
            DisplayError(err);
        });
    };

    //todo: use underscore
    function AddTitles() {
        if ($scope.team.people_TeamMember == undefined || $scope.roles == undefined) {
            return;
        }
        for (var i = 0; i < $scope.team.people_TeamMember.length; i++) {
            if ($scope.team.people_TeamMember[i].defaultTeamRoleId != undefined) {
                {
                    for (var m = 0; m < $scope.roles.length; m++) {
                        if ($scope.team.people_TeamMember[i].defaultTeamRoleId == $scope.roles[m].lookupID) {
                            $scope.team.people_TeamMember[i].lookup = $scope.roles[m].title;
                            break;
                        }
                    }
                }
            }
        }
    };

    //todo: use underscore
    function RemoveTitles() {
        if ($scope.team.people_TeamMember == undefined || $scope.roles == undefined) {
            return;
        }
        for (var i = 0; i < $scope.team.people_TeamMember.length; i++) {
            $scope.team.people_TeamMember[i].lookup = null;
        }
    };
    

    $scope.addTeamMember = function (teamMember) {
       $scope.team.people_TeamMember.unshift({
            TeamId: $scope.teamid,
            Id: 0,
            PersonId: 0,
            Email: teamMember.email,
            Phone: teamMember.phone,
            DefaultTeamRoleId: teamMember.defaultTeamRoleId,
            Person: {
                Name: teamMember.person.name
            }
        });
        $scope.team.people_TeamMember[0].Id = 0;
        $scope.team.people_TeamMember[0].PersonId = 0;
        RemoveTitles();
        TeamServices.PostMember({
            value: $scope.team
        }, $scope.team, function (successResult) {
            $scope.toggleAddMode();
            //refresh
            GetTeam();
            logger.success("Add And Refresh Sucessful");
        }, function (err) {
            DisplayError(err);
        });
    };


    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };
    $scope.deleteTeam = function (team) {
        $routeParams.id = team.id;

        TeamServices.DeleteTeamMember({
            id: team.id
        }, function (successResult) {
            // $scope.toggleEditMode();
            //refresh
            GetTeam();
            logger.success('Deleted Sucessfully');
        }, function (err) {
            DisplayError(err);
        });
    };
    $scope.updateTeam = function (team) {
        if (team.id == 0) {
            $scope.addTeamMember(team);
            return;
        }

        RemoveTitles();

        TeamServices.PutTeam({
            id: team.id
        }, team, function (successResult) {
            $scope.toggleEditMode(team);
            GetTeam();
            logger.success('Update and Refresh Sucessfully');
        }, function (err) {
            DisplayError(err);

        });
    };

}

function teamCtrl($rootScope, $scope, TeamServices, logger) {
    $scope.teams = [];
    $scope.team = [];
    $scope.title = '';
    $scope.addMode = false;


    $scope.toggleAddMode = function () {
        $scope.addMode = !$scope.addMode;
    };

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };

    function GetTeam() {
        TeamServices.GetTeams(function (successResult) {
            $scope.teams = successResult;
        }, function (err) {
            DisplayError(err);
        });
    }

    if ($scope.teams == undefined || ($scope.teams.length <= 0)) {
        GetTeam();
    };


    $scope.AddTeam = function (entity) {
        $scope.team.push({
            teamid: 0,
            title: entity,
        });

        TeamServices.AddTeam({
            value: $scope.team[0].title
        }, null, function (successResult) {
            $scope.toggleAddMode();
            //refresh
            GetTeam();
            logger.success("Add And Refresh Sucessful");
        }, function (err) {
            DisplayError(err);
        });
    };

    $scope.DeleteTeam = function (team) {


        TeamServices.DeleteTeam({
            id: team.id
        }, function (successResult) {
            // $scope.toggleEditMode();
            //refresh
            GetTeam();
            logger.success('Deleted Sucessfully');
        }, function (err) {
            DisplayError(err);
        });
    };

}

function incidentCtrl($rootScope, $scope, IncidentServices, logger) {
    $scope.incidents = [];

    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };



    function GetIncidents() {
        IncidentServices.GetIncidents(function (successResult) {
            $scope.incidents = successResult
        }, function (err) {
            DisplayError(err);
        });
    }

    if ($scope.incidents == undefined || !($scope.incidents.length > 0)) {
        GetIncidents();
    };

    $scope.deleteIncident = function (incident) {
        // $routeParams.id = incident.id;
        $scope.loading = true;

        IncidentServices.DeleteIncident({
            id: incident.id
        }, function (successResult) {
            // $scope.toggleEditMode();
            //refresh
            GetIncidents();
            logger.success('Deleted Sucessfully');

        }, function (err) {
            DisplayError(err);
        });

        $scope.loading = false;

    };

}

function incidentDetailCtrl($rootScope, $scope, $routeParams,$location, IncidentServices, TeamServices, LocationServices, logger, _) {
    $scope.incidentId = $routeParams.id;
    $scope.incident = [];
    $scope.teams = [];

    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };



    //will get get the incident
    function GetIncident() {
        IncidentServices.GetIncident({
            id: $routeParams.id
        }, function (successResult) {

            $scope.incident = successResult;
            GetTeams();
        }, function (err) {
            DisplayError(err);
        });
    }


    //get incident as needed
    if ($scope.incident == undefined || !($scope.incident.length > 0)) {
        $scope.loading = true;
        GetIncident();
        $scope.loading = false;

    }
    ;

    function GetTeams() {
        if ($scope.teams == undefined || !($scope.teams.length > 0)) {
            TeamServices.GetTeams(function (successResult2) {
                $scope.teams = successResult2;

                for (var i = 0; i < $scope.teams.length; i++) {
                    if ($scope.teams[i].id == $scope.incident.team_Id) {
                        //       $scope.select2 = $scope.teams[i];
                        $scope.select2 = $scope.teams[i].id;
                        break;
                    }
                }

            }, function (err) {
                DisplayError(err);
            });
        }
    };


    $scope.addIncident = function () {
        //  var member = $scope.incident.people_IncidentMember.push(IncidentMember);
        // AddIncident();
        // RemoveTitles();
        $scope.loading = true;

        IncidentServices.PostIncident({
            incident: $scope.incident
        }, $scope.incident, function (successResult) {
            $scope.incident = successResult;
            //refresh
            GetIncident();
            logger.success("Add Sucessful");
        }, function (err) {
            DisplayError(err);
        });
        $scope.loading = false;

    };


    $scope.deleteIncident = function (incident) {
        // $routeParams.id = incident.id;
        $scope.loading = true;

        IncidentServices.DeleteIncident({
            id: incident.id
        }, function (successResult) {
            // $scope.toggleEditMode();
            //refresh
            GetIncident();
            logger.success('Deleted Sucessfully');

        }, function (err) {
            DisplayError(err);
        });
        $scope.loading = false;
    };


    $scope.updateIncident = function (incident) {
        //  RemoveTitles();
        $scope.loading = true;

        IncidentServices.PutIncident({
            id: incident.id
        }, $scope.incident, function (successResult) {
            GetIncident();
            logger.success("Update Sucessful");
        }, function (err) {
            DisplayError(err);

        });
        $scope.loading = false;

    };

    //delete location and refresh 
    $scope.deleteLocation = function (locationId) {

        $scope.loading = true;
        LocationServices.DeleteLocation({
            id: locationId
        }, function (successResult) {
            //refresh
            GetIncident();
            logger.success('Deleted Sucessfully');
            $scope.loading = false;
        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };


    $scope.LastIncident = function (ev)
    { }

    $scope.NextIncident = function (ev)
    { }

    $scope.ListOfIncidents = function ()
    { 
        $scope.changeRoute = function () { $location.path("/Incidents"); }
    }
    
    $scope.GotoLocation = function (id)
    {
        var loc = "/LocationDetail/:" + id;
        $scope.changeRoute = function () { $location.path(loc); }
        
    }
    
    

}


function locationDetailCtrl($rootScope, $scope, $routeParams, LocationServices, AdminServices, logger,_) {

    //setup values
    $scope.incidentId = $routeParams.id;

    $scope.isVisible = true;
    $scope.loading = true;
    $scope.location = [];
    $scope.hstep = 1;
    $scope.mstep = 15;


    $scope.checksave = function () {
        if ($scope.form.$dirty)
        {
            return true;
        }
    }

    $scope.toggleVisible = function () {
        $scope.IsVisible = !$scope.IsVisible;
    };

    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };


    //-----------------------------------
    // Get Location
    //-----------------------------------
    function GetLocation() {
        LocationServices.GetLocation({
            id: $routeParams.id
        }, function (successResult) {

            $scope.location = successResult;
            AddTitles();
            $scope.loading = true;
            $scope.form.$setPristine();
        }, function (err) {
            DisplayError(err);
        });
    }

    //------------------------------------------------------------
    //GET LATLONG
    //------------------------------------------------------------
    $scope.codeAddress = function () {

        var lataddr = $scope.location.street + ", " + $scope.location.city + " OR";

        var result = LocationServices.GetLatLong({ address: lataddr },
         function (successResult) {
             //underscore
             var slat = _.reduce(successResult[0], function (memo, num) { return memo + num; }, '');
             var slong = _.reduce(successResult[1], function (memo, num) { return memo + num; }, '');
             $scope.location.geoLocationLat = slat;
             $scope.location.geoLocationLong = slong;
             $scope.form.setDirty();

         }, function (err) {
             DisplayError(err);
         })
    };


    //--------------------------------------------------------
    //support tables
    //--------------------------------------------------------
    $scope.locationtype = AdminServices.GetByDesc({
        desc: "Location"
    }, function (successResult) {
    }, function (err) {
        DisplayError(err);
    });
    $scope.locationStatus = AdminServices.GetByDesc({
        desc: "Location Status"
    }, function (successResult) {
    }, function (err) {
        DisplayError(err);
    });

    $scope.hazards = AdminServices.GetByDesc({
        desc: "Hazard"
    }, function (successResult) {
    }, function (err) {
        DisplayError(err);
    });

    //
    // pull location data
    //
    if ($scope.location == undefined || !($scope.location.length > 0)) {

        if ($routeParams.id == 0) {
            LocationServices.GetNewLocation({
                incidentId: $routeParams.id2
            }, function (successResult) {

                $scope.location = successResult;
                AddTitles();
                $scope.loading = true;
                $scope.form.$setPristine();
            }, function (err) {
                DisplayError(err);
            });
        }
        else {
            GetLocation();
        }
    };



    $scope.toggleSelection = function toggleSelection(hazard, checked) {
        var index = 0;
        var rec;
        //ar rec = _.findWhere($scope.location.locationHazards, { hazardTypeID: hazard.lookupID });
        if (rec !== undefined) {
            var target = angular.element(this.$id);
            var tk = document.getElementById(this.$id);
            target.checked = true;
        }
    }

    //add location
    $scope.addLocation = function () {
        $scope.loading = true;
        LocationServices.PostLocation({
            value: $scope.location
        }, $scope.location, function (successResult) {
            $routeParams.id = successResult.id;
            GetLocation();
            logger.success("Add And Refresh Sucessful");
            $scope.loading = false;

        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };


    //delete location and refresh 
    $scope.deleteLocation = function (location) {
        $routeParams.id = location.id;
        $scope.loading = true;
        LocationServices.DeleteLocation({
            id: location.id
        }, function (successResult) {
            //refresh
            GetLocation();
            logger.success('Deleted Sucessfully');
            $scope.loading = false;

        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };

    //updatelocation
    $scope.updateLocation = function (location) {

        $scope.loading = true;
        if (location.id == 0) {
            location.locationHazards = _.reject(location.locationHazards, function (el) { return el.hazardTypeID === 0; });
            $scope.addLocation(location);
            return;
        }

        LocationServices.PutLocation({
            id: location.id
        }, $scope.location, function (successResult) {
            GetLocation();

            $scope.loading = false;
            logger.success('Update and Refresh Sucessfully');

        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };


    function AddTitles() {
        if ($scope.location.locationHazards == undefined || $scope.hazards == undefined) {
            return;
        }

        for (var i = 0; i < $scope.location.locationHazards.length; i++) {
            var rec = _.findWhere($scope.hazards, { lookupID: $scope.location.locationHazards[i].hazardTypeID });
            $scope.location.locationHazards[i].lookup = rec.title;

        }
    }
}


//
//
//
function victimsCtrl($rootScope, $scope, $routeParams, VictimsServices, AdminServices, logger,_) {
    $scope.locationId = $routeParams.id;
    $scope.addMode = false;
    $scope.isVisible = true;
    $scope.loading = true;
    $scope.location = [];


    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }
    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };

    $scope.toggleVisible = function () {
        $scope.IsVisible = !$scope.IsVisible;
    };
    $scope.toggleAddMode = function () {
        $scope.addMode = !$scope.addMode;
    };
    $scope.toggleEditMode = function (victim) {
        victim.editMode = !victim.editMode;
    };


    $scope.checksave = function () {
        if ($scope.form.$dirty)
        { return true; }
    }

    $scope.victimStatus = AdminServices.GetByDesc({
        desc: "Victim Status"
    }, function (successResult) {

    }, function (err) {
        var reason = err.message;
        var detail = err.detail;
        logger.error(err, reason);
    });
    //AdminServices.GetByDesc("Victim Status");
    $scope.victimGender = AdminServices.GetByDesc({
        desc: "Gender"
    }, function (successResult) {
    }, function (err) {
        DisplayError(err);
    });//= AdminServices.GetByDesc("Gender");
    $scope.victimAge = AdminServices.GetByDesc({
        desc: "Age Range"
    }, function (successResult) {
    }, function (err) {
        DisplayError(err);
    });


    function GetVictims() {
        $scope.loading = true;

        $scope.loading = true;
        VictimsServices.GetVictims({
            id: $routeParams.id
        }, function (successResult) {

            $scope.victims = successResult;
            // $scope.victim.editMode = true;
            AddTitles();
            $scope.loading = false;
        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });

    }


    if ($scope.victims == undefined || !($scope.victims.length > 0)) {
        GetVictims();
    }


    $scope.addVictim = function (victim) {
        $scope.loading = true;
        victim.locationId = $scope.locationId;
        victim.location = [];
        victim.victimId = 0;
        RemoveTitles();
        VictimsServices.PostVictim({
            value: victim
        }, victim, function (successResult) {
            $scope.toggleAddMode();
            $scope.victim.editMode = true;
            GetVictims();
            // $scope.victim = successResult;
            logger.success("Add And Refresh Sucessful");
            $scope.loading = false;
        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };

    function AddTitles() {
        if ($scope.victims == undefined || $scope.victimAge == undefined) {
            return;
        }

        for (var i = 0; i < $scope.victims.length; i++) {
            var rec = _.findWhere($scope.victimStatus, { lookupID: $scope.victims[i].victimStatusID });
            $scope.victims[i].lookup1 = rec.title;
            var rec2 = _.findWhere($scope.victimGender, { lookupID: $scope.victims[i].genderID });
            $scope.victims[i].lookup2 = rec2.title;
            var rec3 = _.findWhere($scope.victimAge, { lookupID: $scope.victims[i].ageRangeID });
            $scope.victims[i].lookup = rec3.title;

        }
    };

    $scope.deleteVictim = function (victim) {
        $routeParams.id = victim.locationId;
        $scope.loading = true;
        VictimsServices.DeleteVictim({
            id: victim.id
        }, function (successResult) {
            // 
            $scope.victim.editMode = true;
            //refresh
            GetVictims();
        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };


    $scope.updateVictim = function (victim) {
        $scope.loading = true;

        if (victim.id == 0) {

            victim.people_Victim = _.reject(victim.people_Victim, function (el) { return el.GenderID === 0; });
            $scope.addVictim(victim);
            return;
        }

        RemoveTitles();

        VictimsServices.PutVictim({
            id: victim.id
        }, victim, function (successResult) {

            GetVictims();
            $scope.toggleEditMode(victim);
            //  $scope.victim.editMode = true;
            $scope.loading = false;
            logger.success('Update and Refresh Sucessfully');
        }, function (err) {
            DisplayError(err);
            $scope.loading = false;
        });
    };

    function RemoveTitles() {
        if ($scope.victims == undefined || $scope.victimAge == undefined) {
            return;
        }

        for (var i = 0; i < $scope.victims.length; i++) {
            $scope.victims[i].lookup1 = null;
            $scope.victims[i].lookup2 = null;
            $scope.victims[i].lookup = null;
            $scope.$apply();
        }
    }
    //;


}


function aboutCtrl($rootScope, $scope) {
}


function adminCtrl($rootScope, $scope, $routeParams, AdminServices, logger) {
    $scope.loading = true;
    //$scope.userRoles = Auth.userRoles;

    $scope.admins = [];
    $scope.desc = $routeParams.id;
    $scope.addMode = false;
    $scope.isVisible = true;

    $scope.toggleVisible = function () {
        $scope.IsVisible = !$scope.IsVisible;
    }

    //---------------------------------------------------------
    // Error related code
    //---------------------------------------------------------

    //displays error info
    function DisplayError(err) {
        var reason = err.message;
        var detail = err.detail;
        if (reason === "Validation error") {
            reason = handleSaveValidationError(err);
        } else if (detail && detail.ExceptionType && detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
            reason = "Another user, perhaps the server, " + "may have deleted one or all of the todos." + " You may have to restart the app.";
        } else {
            reason = "Failed to save changes: " + reason + " You may have to restart the app.";
        }
        logger.error(err, reason);
    }

    function handleSaveValidationError(error) {
        var message = "Not saved due to validation error";
        try {
            var firstErr = error.entitiesWithErrors[0].entityAspect.getValidationErrors()[0];
            message += ": " + firstErr.errorMessage;
        } catch (e) {
        }
        return message;
    };


    //---------------------------------------
    //  Get Admin
    //---------------------------------------
    function GetAdmin() {
        $scope.admins = AdminServices.GetByDesc({
            desc: $routeParams.id
        }, function (successResult) {
            //$scope.IsVisible = true;
        }, function (err) {
            DisplayError(err);
            // $scope.IsVisible = true;
        });
    }

    //todo initialize default values
    //add a watch instead of a toggle?
    $scope.toggleAddMode = function () {
        $scope.addMode = !$scope.addMode;
    };

    $scope.toggleEditMode = function (admin) {
        admin.editMode = !admin.editMode;
    };




    if ($scope.admins == undefined || !($scope.admins.length > 0)) {
        //$scope.IsVisible = false;
        GetAdmin();
    };
    $scope.addAdmin = function () {

        $scope.admin.discriminator = $routeParams.id;
        if ($scope.admins != undefined || ($scope.admins.length > 0)) {
            $scope.admin.lookupTypeID = $scope.admins[0].lookupTypeID;
        }
        AdminServices.Post({ value: $scope.admin }, $scope.admin, function (successResult) {
            // do something on 
            $scope.toggleAddMode();
            $scope.admin = {};
            GetAdmin();
            logger.success("successfully saved");
            //  logger.log(successResult);
        }, function (err) {
            DisplayError(err);
        });
    };


    $scope.deleteAdmin = function (admin) {
        $routeParams.lookupID = admin.lookupID;
        // $location.path('api/admin/' + admin.lookupID);
        AdminServices.Delete({ id: admin.lookupID }, function (successResult) {
            // do something on success
            GetAdmin();
            logger.success('Deleted Sucessfully');
        }, function (err) {
            DisplayError(err);
        });
    };

    $scope.updateAdmin = function (admin) {
        //   $location.path('api/admin/' + admin.lookupID);
        AdminServices.Put({
            id: admin.lookupID
        }, admin, function (successResult) {
            // do something on success
            GetAdmin()
            logger.success('Updated Sucessfully');
        }, function (err) {
            DisplayError(err);
        });

    };

    function initializeAdd(admin) {
        admin.desc = $routeParams.id;
        if ($scope.admins != undefined || ($scope.admins.length > 0)) {
            admin.lookupTypeID = $scope.admins[0].lookupTypeID;
        }
    };


};

